import { SchemaManage } from '@/components/SchemaComponent';
import { useEffect, useMemo, useRef, useState } from 'react';
import { connect } from 'umi';
import { ManageCommonAPI } from '@/pages/type';
import { fieldFlowExport, getKeyRouter, getTenantID } from '@/utils';
import { history } from 'umi';
import { PlusOutlined, UploadOutlined, FileProtectOutlined, FileDoneOutlined } from '@ant-design/icons';
import { ContractManageAPI } from '../common/type';
import { ContractSignModal } from './ContractSignModal';
import { message } from 'antd';
import { CancelModal } from '@/components/CancelModal';
import { ILoadMapTypeAll } from '@/common';
import { NtkoPlugin } from '@/common/NtkoPluginType';
import '../common/manageStyle.less';
import { TipsErrorModalNew } from '@/components/TipsErrorModalNew';
import { getBaseUrl } from '@/services/urlconst';
import {
  contractManageService,
  deleteContractService,
  exportMcontractService,
  getMcontractByIDService,
  invalidContractService,
  sealContractService,
  settingPrintNumService,
  finishContractService,
} from '../services';
import {
  ManagePageTypeConfig,
  deleteModalOnOK,
  editModifyContract,
  getTableColumns,
  invalidModalOnOk,
  ntkoQueryParams,
  renderTipName,
  useDataSourceTable,
  useOfdWord,
  finishModalOnOK,
} from '../mconfig';
import { OpenSuperModal } from './OpenSuperModal';
import { ContractUrfeListDrawer } from './ContractUrfeListDrawer';
import { readReadShowFileService } from '@/services/BaseLayout';
import moment from 'moment';

const ContractManageView: React.FC<ContractManageAPI.IManageType> = ({ curRes, locationProps }) => {
  const schemaManageRef: any = useRef();

  const manageFixStyle: string = 'contract-managestyle-';

  /** 轻阅读预览 */
  const { readReadShowFileRun } = readReadShowFileService();

  /**轻阅读预览 */
  const onOpenReadOfdWord = (fieldUrl: string) => {
    readReadShowFileRun({ fieldPath: `${getBaseUrl()}${fieldUrl}` });
    // readReadShowFileRun({ fieldPath: `http://222.186.101.211:20103${fieldUrl}` });
  };

  /** 申请页ref */
  const tipErrorModalRef: any = useRef();

  /** 获取页面路由参数 */
  const pageParams = useMemo(() => {
    const pageInfo: Record<string, any> | null = ManagePageTypeConfig(locationProps?.pathname);
    return pageInfo;
  }, [locationProps?.pathname]);

  /**  获取管理页数据 */
  const { data, loading, pagination, searchList, getContractData, reloadRefresh, allSearchParams } = contractManageService(curRes, pageParams);

  /** 是否打开支付弹框 */
  const [openSignModalObj, setOpenSiginModalObj] = useState<Record<string, any>>({
    isShowModal: false,
    selectRow: {},
  });

  /** 作废 */
  const [openCancelModal, setOpenCancelModal] = useState<Record<string, any>>({
    openModal: false,
    selectRows: {},
  });

  /** 一键督办提示框 */
  const [superVising, setSuperVisingModal] = useState<Record<string, any>>({
    checkRowObj: {},
    isShowModal: false,
  });

  /** 保存点击数据 */
  const [saveClickInfo, setSaveClickInfo] = useState<Record<string, any>>({});

  /** 查看督办记录 */
  const [openUrgeInfoDrawer, setOpenUrgeInfoDrawer] = useState<Record<string, any>>({
    openDrawer: false,
    checkRowObj: {},
  });

  /** 签发提示框 */
  const [openTipInfoModal, setOpenTipInfoModal] = useState<Record<string, any>>({
    checkRowObj: {},
    showModal: false,
    tipType: null, // delete:删除   revoke:撤销  finish:归档
  });

  /**保存选中数据 */
  const [selectRowKeys, setSelectRowKeys] = useState<Record<string, any>>({ rowKeysList: [], valList: [] });

  /** 保存变更合同ID */
  const [modifyInfoDetail, setModifyInfoDetail] = useState<Record<string, any>>({});

  /** 保存展示的表格数据 */
  const [dataSourceTable, setDataSourceTable] = useState<Record<string, any>[]>([]);

  /** 保存表格展开行的key值 */
  const [tableExpantKeys, setTableExpantKeys] = useState<string[]>([]);

  /**  重置搜索表单方法 */
  const onReset = (values: any) => {
    getContractData({ ...values, state: pageParams?.state?.toString() });
  };

  /**  搜索列表 */
  const onSearch = (request: ManageCommonAPI.IGridRequestType) => {
    getContractData({ ...request });
  };

  /** 分页change 方法 */
  const onPageChange = (current: any, pageSize: any, params: any) => {
    getContractData({ pageSize, current, ...params });
  };

  /** 刷新管理页面 */
  const reloadManage = () => {
    reloadRefresh();
  };

  /** 详情回调 */
  const detailsCallback = (res: any) => {
    if (res && res?.msgFlag) {
      history.push({
        pathname: `/contractController/getMcontractByID/:${getKeyRouter()}${getKeyRouter()}`,
        state: {
          pageType: 'detail',
          id: modifyInfoDetail?.clickType ? modifyInfoDetail?.pID : modifyInfoDetail?.id,
          pageInfo: modifyInfoDetail,
          pIDDetailInfo: {
            ...res?.obj,
          },
          returnPathName: locationProps?.pathname,
        },
      });
      setModifyInfoDetail({});
    } else {
      message.error(res?.msg);
    }
  };

  /** 获取详情 */
  const { getMcontractByIDRun, getMcontractByIDLoading } = getMcontractByIDService(detailsCallback);

  /** 引入在线预览 */
  const ntkoBrowser = useMemo(() => {
    const { ntkoBrowser } = NtkoPlugin(() => {});
    return ntkoBrowser;
  }, []);

  /** 设置打印份数回调 */
  const printCallback = (res: any) => {
    if (res && res?.code == 1) {
      message.success(res?.message);
    } else {
      message.error('打印份数设置失败！');
    }
  };

  /** 设置打印份数 */
  const { settingDocPrintNumLoading, settingDocPrintNumRun } = settingPrintNumService(printCallback);

  /** 一键督办参数处理 */
  const handleOversightBtnClick = () => {
    if (selectRowKeys?.rowKeysList?.length > 0) {
      setSuperVisingModal({
        isShowModal: true,
        selectRow: selectRowKeys,
      });
    } else {
      message.warning('请至少选择一个合同进行提醒！');
    }
  };

  /** 回调 */
  const stampCallback = (res: any) => {
    if (res && res?.msgFlag) {
      message.success(res?.msg);
      settingDocPrintNumRun(res?.obj);
      reloadManage();
    } else {
      message.error(res?.msg);
    }
  };

  /** 引入接口 */
  const { sealContractLoading, sealContractRun } = sealContractService(stampCallback);

  /** 签章文件保存回调 */
  const uploadFileCallback = (res: any, rowInfo: Record<string, any>) => {
    if (res?.fileURL && rowInfo?.id) {
      sealContractRun({
        sealURL: res?.fileURL,
        id: rowInfo?.id,
        state: `${getTenantID()}${ILoadMapTypeAll.CONTRACT_STATE}1003`,
        versionNum: rowInfo?.versionNum,
      });
    } else {
      message.error('保存失败！');
    }
  };

  /** 处理转换文件 */
  const { convertOfdRun, convertOfdLoading, sealFieldLoading, onPrentOFD } = useOfdWord(saveClickInfo, reloadManage, uploadFileCallback);

  /** 点击编辑变更解除方法 */
  editModifyContract(modifyInfoDetail, setModifyInfoDetail);

  /** 表格操作按钮点击方法 */
  const onOptClick: ContractManageAPI.IOperationClick = {
    onView: (resObj) => {
      if (resObj?.changeWay == 0 || resObj?.changeWay == 1) {
        setModifyInfoDetail(resObj);
        getMcontractByIDRun({
          id: resObj?.pID,
        });
      } else {
        history.push({
          pathname: `/contractController/getMcontractByID/:${getKeyRouter()}${getKeyRouter()}`,
          state: {
            pageType: 'detail',
            id: resObj?.id,
            pageInfo: resObj,
            pIDDetailInfo: {
              ...resObj,
            },
            returnPathName: locationProps?.pathname,
          },
        });
      }
    },
    onEdit: (resObj) => {
      if (resObj?.changeWay == 0 || resObj?.changeWay == 1) {
        setModifyInfoDetail({
          ...resObj,
          clickModify: true,
          changeWay: resObj?.changeWay,
        });
      } else {
        let params: any = {
          pageType: 'add',
          id: resObj?.id,
          returnPathName: locationProps?.pathname,
        };
        if (resObj.recordFlag == 1) params['updateType'] = 'UpdateRepairAdd';
        history.push({
          pathname: `/contractController/edit/:${getKeyRouter()}${getKeyRouter()}`,
          state: params,
        });
      }
    },
    onSignBtn: (resObj) => {
      setOpenSiginModalObj({
        isShowModal: true,
        selectRow: resObj,
      });
    },
    onModify: (resObj) => {
      setModifyInfoDetail({
        ...resObj,
        clickModify: true,
        changeWay: 0,
      });
    },
    onBreak: (resObj) => {
      setModifyInfoDetail({
        ...resObj,
        clickModify: true,
        changeWay: 1,
      });
    },
    onPidEye: (resObj) => {
      setModifyInfoDetail({
        ...resObj,
        clickType: true,
      });
      getMcontractByIDRun({
        id: resObj?.pID,
      });
    },
    onCancel: (resObj) => {
      setOpenCancelModal({
        openModal: true,
        selectRows: resObj,
      });
    },
    onNtko: (resObj, fieldName) => {
      const { ntkoWordUrl } = ntkoQueryParams(resObj, curRes, fieldName, true);
      const extensBool = ntkoBrowser.ExtensionInstalled();
      if (extensBool) {
        ntkoBrowser?.openWindow(ntkoWordUrl, false, '', '');
      }
    },
    onPrint: (resObj) => {
      // onPrentWord(resObj);
      onPrentOFD(`${getBaseUrl()}${resObj?.sealURL}`, 'print', resObj, uploadFileCallback);
    },
    onStamp: (resObj) => {
      setSaveClickInfo(resObj);
      if (resObj?.sealURL) {
        onPrentOFD(resObj?.sealURL?.includes('http') ? `${resObj?.sealURL}` : `${getBaseUrl()}${resObj?.sealURL}`, 'sealURL', resObj, uploadFileCallback);
        // onPrentOFD(`${getBaseUrl()}${resObj?.contractURL}`, 'contractURL', resObj, uploadFileCallback);
      } else {
        convertOfdRun(`${getBaseUrl()}${resObj?.contractURL}`);
      }
    },
    onDelete: (resObj) => {
      setOpenTipInfoModal({
        checkRowObj: resObj,
        showModal: true,
        tipType: 'delete',
      });
    },
    onRevoke: (resObj) => {
      setOpenTipInfoModal({
        checkRowObj: resObj,
        showModal: true,
        tipType: 'revoke',
      });
    },
    onDownload: (resObj) => {
      const { ntkoWordUrl } = ntkoQueryParams(resObj, curRes, 'scanURL');
      const extensBool = ntkoBrowser.ExtensionInstalled();
      if (extensBool) {
        ntkoBrowser?.openWindow(ntkoWordUrl, false, '', '');
      }
    },
    onUrge: (resObj) => {
      setOpenUrgeInfoDrawer({
        openDrawer: true,
        checkRowObj: resObj,
      });
    },
    onfinish: (resObj) => {
      setOpenTipInfoModal({
        checkRowObj: resObj,
        showModal: true,
        tipType: 'finish',
      });
    },
    onOpenRead: (resObj) => {
      onOpenReadOfdWord(resObj?.contractURL);
    },
  };

  /**
   * 监听从合同统计列表带过来的数据，放到搜索框中进行搜索
   * */
  useEffect(() => {
    if (locationProps?.state?.searchInitParam && schemaManageRef?.current) {
      let params = locationProps?.state?.searchInitParam;
      //快捷搜索中的默认值
      let formObj = {
        createDepartmentID: params?.createDepartmentID,
      };
      //更多搜索中的默认值
      let drawFormObj = {
        currencyType: params?.currencyType,
        businessType: params?.businessType,
        capitalDir: params?.capitalDir,
        realTime: [moment(params?.realBeginTime), moment(params?.realFinishTime)],
      };
      /**过滤无用数据 */
      Object.keys(drawFormObj)?.forEach((item: any) => {
        if (drawFormObj[item] != 0 && !drawFormObj[item]) {
          delete drawFormObj[item];
        }
      });
      schemaManageRef?.current?.setSearch(formObj, drawFormObj);
    } else {
      schemaManageRef?.current?.setSearch({});
    }
  }, [locationProps?.state]);

  /** 获取columns方法 */
  const columns: Record<string, any>[] = useMemo(() => {
    return getTableColumns(curRes, onOptClick, manageFixStyle, pageParams);
  }, [curRes, manageFixStyle, pageParams]);

  /** 导出回调 */
  const exportCallback = (res: any) => {
    fieldFlowExport(res, '合同信息数据.xlsx');
  };

  /**引入导出接口*/
  const { exportMcontractLoading, exportMcontractRun } = exportMcontractService(exportCallback);

  /**操作按钮列表 */
  const actionList: ManageCommonAPI.IActionList = useMemo(() => {
    return [
      {
        title: '添加',
        visible: curRes?.['/contractController/add'] && pageParams?.addBtnDom,
        type: 'primary',
        icon: <PlusOutlined />,
        onClick: () => {
          history.push({
            pathname: `/contractController/add/:${getKeyRouter()}${getKeyRouter()}`,
            state: {
              pageType: 'add',
              returnPathName: locationProps?.pathname,
            },
          });
        },
      },
      {
        title: '导出',
        visible: pageParams?.exportBtnDom && curRes?.['/contractController/exportMcontract/{fieldName}'],
        type: 'primary',
        icon: <UploadOutlined />,
        onClick: () => {
          if (dataSourceTable && dataSourceTable?.length > 0) {
            exportMcontractRun(allSearchParams);
          } else {
            message.warning('导出数据为空，请刷新重试！！！');
          }
        },
      },
      {
        title: '超期提醒',
        visible: pageParams?.oversightBtnDom && curRes?.['/contractController/batchHandle'],
        type: 'primary',
        icon: <FileProtectOutlined />,
        onClick: handleOversightBtnClick,
      },
      {
        title: '补录',
        visible: pageParams?.addBtnDom && curRes?.['/contractController/addRecord'],
        type: 'primary',
        icon: <FileDoneOutlined />,
        onClick: () => {
          history.push({
            pathname: `/contractController/seal/:${getKeyRouter()}${getKeyRouter()}`,
            state: {
              pageType: 'add',
              updateType: 'UpdateRepairAdd',
              returnPathName: locationProps?.pathname,
            },
          });
        },
      },
    ];
  }, [curRes, selectRowKeys, allSearchParams, dataSourceTable]);

  /** 签发按钮关闭 */
  const tipOnClose = () => {
    setOpenTipInfoModal({
      checkRowObj: {},
      showModal: false,
      tipType: null,
    });
  };

  /** 提示弹框回调 */
  const tipModalCallback = (res: any) => {
    if (res && res?.msgFlag) {
      message.success(res?.msg);
      reloadManage();
      tipOnClose();
    } else {
      message.error(res?.msg);
    }
  };

  /** 引入删除接口 */
  const { deleteContractRun } = deleteContractService(tipModalCallback);

  /** 引入合同归档接口 */
  const { finishContractRun } = finishContractService(tipModalCallback);

  /** 引入撤销接口 */
  const { invalidContractRun } = invalidContractService(tipModalCallback);

  /** 处理是否有子合同 */
  const { onExpandTable, childLoading } = useDataSourceTable(data?.rows, dataSourceTable, setDataSourceTable, tableExpantKeys, setTableExpantKeys);

  /**设置督办多选框 */
  const oversightMemo = useMemo(() => {
    let rowSelectInfo: Record<string, any> = {};
    if (pageParams?.oversightBtnDom) {
      rowSelectInfo = {
        rowSelection: {
          type: 'checkBox',
          selectedRowKeys: selectRowKeys?.rowKeysList,
          onChange: (selectedRowKeys: React.Key[], selectedValList) => {
            setSelectRowKeys({
              rowKeysList: selectedRowKeys,
              valList: selectedValList,
            });
          },
        },
      };
    }
    return rowSelectInfo;
  }, [pageParams?.oversightBtnDom, selectRowKeys]);

  return (
    <div
      style={{
        width: '100%',
        height: '100%',
        overflow: 'hidden',
        position: 'relative',
      }}
    >
      <div className={`${manageFixStyle}`}>
        <SchemaManage
          ref={schemaManageRef}
          searchProps={{
            switchList: [],
            searchList,
            onSwitch: () => {},
            onReset,
            onSearch,
          }}
          actionList={actionList}
          tableProps={{
            columns,
            dataSource: dataSourceTable,
            loading:
              loading ||
              getMcontractByIDLoading ||
              convertOfdLoading ||
              sealFieldLoading ||
              sealContractLoading ||
              settingDocPrintNumLoading ||
              childLoading ||
              exportMcontractLoading,
            pagination: pagination as any,
            rowKey: 'id',
            onPageChange, //分页onchange
            expandable: {
              // expandIcon: manageTableExpandIcon,
              onExpand: onExpandTable,
              expandedRowKeys: tableExpantKeys,
            },
            ...oversightMemo,
          }}
        />
      </div>

      {/* 提示框 */}
      {openTipInfoModal?.showModal && (
        <TipsErrorModalNew
          ref={tipErrorModalRef}
          modalLoading={false}
          onClose={tipOnClose}
          modalOnOK={
            openTipInfoModal?.tipType == 'delete'
              ? () => {
                  deleteModalOnOK(openTipInfoModal?.checkRowObj, deleteContractRun);
                }
              : openTipInfoModal?.tipType == 'revoke'
              ? () => {
                  invalidModalOnOk(openTipInfoModal?.checkRowObj, invalidContractRun);
                }
              : openTipInfoModal?.tipType == 'finish'
              ? () => {
                  finishModalOnOK(openTipInfoModal?.checkRowObj, finishContractRun);
                }
              : () => {}
          }
          tipTextColor="#000"
          modalTip={renderTipName(openTipInfoModal?.tipType, openTipInfoModal?.checkRowObj)}
        />
      )}

      {/* 上传合同扫描件 */}
      {openSignModalObj?.isShowModal && (
        <ContractSignModal
          onClose={() => {
            setOpenSiginModalObj({
              isShowModal: false,
              selectRow: {},
            });
          }}
          selectRowInfo={openSignModalObj?.selectRow}
          reloadManage={reloadManage}
        />
      )}

      {/* 作废弹框 */}
      {openCancelModal?.openModal && (
        <CancelModal
          onClose={() => {
            setOpenCancelModal({
              openModal: false,
              selectRows: {},
            });
          }}
          checkRows={openCancelModal?.selectRows}
          reloadManage={reloadManage}
          modalTitle="合同作废"
          cancelRequestUrl="/contractController/cancel"
          cancelRequestType="PUT"
          cancelFormReasonRequired={true}
          cancelTypeDic={`${ILoadMapTypeAll.CONTRACT_CANCELTYPE}`}
          cancelRequestBody={{
            // workflowID: openCancelModal?.selectRows?.workflowID,
            pID: openCancelModal?.selectRows?.pID,
            orderType: openCancelModal?.selectRows?.orderType,
            businessType: openCancelModal?.selectRows?.businessType,
            state: `${getTenantID()}${ILoadMapTypeAll.CONTRACT_STATE}1007`,
          }}
        />
      )}

      {/* 一键督办 弹框 */}
      {superVising?.isShowModal && (
        <OpenSuperModal
          onClose={() => {
            setSuperVisingModal({
              isShowModal: false,
              selectRow: {},
            });
          }}
          selectRowInfo={selectRowKeys?.valList}
          reloadManage={reloadManage}
          setSelectRowKeys={setSelectRowKeys}
        />
      )}

      {/* 督办记录 */}
      <ContractUrfeListDrawer
        onClose={() => {
          setOpenUrgeInfoDrawer({
            openDrawer: false,
            checkRowObj: {},
          });
        }}
        openDrawer={openUrgeInfoDrawer?.openDrawer}
        checkRowObj={openUrgeInfoDrawer?.checkRowObj}
      />
    </div>
  );
};

export default connect(({ baseLogin }: Record<string, any>) => ({
  curRes: baseLogin?.permissions,
}))(ContractManageView);
